package com.yc.spring.bank.dao;

import com.yc.spring.bank.bean.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.DataClassRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountDao {

    @Resource
    JdbcTemplate jdbcTemplate;

    public void insert(Account account) {
        String sql = "insert into bank_account values(?,?,?)";
        jdbcTemplate.update(sql,
                account.getId(),
                account.getPassword(),
                account.getBalance());
    }

    public Account selectById(String id) {
        String sql = "select * from bank_account where id=?";
        // BeanPropertyRowMapper 自动将字段值注入到对象属性中
        List<Account> query = jdbcTemplate.query(
                sql,
                new BeanPropertyRowMapper<Account>(Account.class),
                id);
        return query.isEmpty() ? null : query.get(0);
    }

    public int update(String id, Double money){
        String sql = "update bank_account set balance = balance + ? where id=?";
        return jdbcTemplate.update(sql, money, id);
    }

    public Account selectByIdAndPwd(String id, String password) {
        String sql = "select * from bank_account where id=? and password=?";
        // BeanPropertyRowMapper 自动将字段值注入到对象属性中
        List<Account> query = jdbcTemplate.query(
                sql,
                new BeanPropertyRowMapper<Account>(Account.class),
                id, password);
        return query.isEmpty() ? null : query.get(0);
    }
}
